package com.demo8.basic.enums;

import com.demo8.basic.utils.StringUtils;
import lombok.Getter;
import lombok.ToString;

import java.util.Arrays;
import java.util.Objects;

@ToString
@Getter
public enum CaptchaEnum {
    IMAGE("image", "图片验证码"),
    EMAIL("email", "邮箱验证码"),
    SMS("sms", "短信验证码");


    private final String type;
    private final String msg;

    CaptchaEnum(String type, String msg) {
        this.type = type;
        this.msg = msg;
    }

    /**
     * 根据code获取枚举实例
     *
     * @param type 验证码类型编码
     * @return 对应的枚举实例
     * @throws IllegalArgumentException 如果找不到对应的枚举
     */
    public static CaptchaEnum of(String type) {
        if (StringUtils.isBlank(type)) {
            throw new IllegalArgumentException("验证码类型编码不能为null");
        }

        return Arrays.stream(values())
                .filter(captchaEnum -> Objects.equals(captchaEnum.type, type))
                .findFirst()
                .orElseThrow(() -> new IllegalArgumentException("无效的验证码类型编码: " + type));
    }

    /**
     * 安全地根据code获取枚举实例，找不到时返回null
     */
    public static CaptchaEnum ofNullable(String type) {
        if (StringUtils.isBlank(type)) {
            return null;
        }

        return Arrays.stream(values())
                .filter(captchaEnum -> Objects.equals(captchaEnum.type, type))
                .findFirst()
                .orElse(null);
    }

    /**
     * 检查code是否存在
     */
    public static boolean contains(String type) {
        if (StringUtils.isBlank(type)) {
            return false;
        }

        return Arrays.stream(values())
                .anyMatch(captchaEnum -> Objects.equals(captchaEnum.type, type));
    }


}
